#!/bin/bash


export PATH=/opt/bind/bin:/bin:/usr/bin


print_usage()
{
echo -e "
Usage: $(basename $0) zonename master1[/master2[/master3...]] -q|-t

    -q: query SOA of zone
    -t: transfer zone
"

}


if [ $# -ne 3 ]; then print_usage; exit 1; fi

zone=$1
masters=$(echo $2 | sed -e 's/\// /g')
option=$(echo $3 | sed -e 's/^-//')
QUERY="NO"
TRANSFER="NO"

if [ "X$(uname -s)" == "XSunOS" ]; then 
    GREP="/usr/xpg4/bin/grep"
else
    GREP="/bin/grep"
fi

. /etc/named/IT_DNS_SERVERS

if echo $option | $GREP -q "q"; then QUERY="YES"; fi
if echo $option | $GREP -q "t"; then TRANSFER="YES"; fi

echo -e "\nVerify whether zone \"$zone\" is configured...\t\c "

/usr/local/sbin/zonecat -T | $GREP -q "^${zone}[[:space:]]\{1,\}"
if [ $? -eq 0 ]; then echo Yes; else echo No; fi

if [ "${QUERY}" == "YES" ]; then
    echo -e "\nVerify whether zone \"$zone\" on its master servers is able to be queried..." 
    for itmaster in $(echo $DNS_PRIMARY_MASTER $DNS_PSEUDO_MASTERS); do
        for remote in $(echo $masters); do
            echo -e "  $itmaster tries querying $remote via 53/tcp...\t\c"
            echo "dig @${remote} -t soa $zone +tcp +short 2>/dev/null" \
		        | ssh $itmaster bash 2>/dev/null | head -1 | $GREP -q "^[A-Za-z0-9]"
            if [ $? -eq 0 ]; then echo Success; else echo Failure; fi
            echo -e "  $itmaster tries querying $remote via 53/udp...\t\c"
            echo "dig @${remote} -t soa $zone +notcp +short 2>/dev/null" \
                | ssh $itmaster bash 2>/dev/null | head -1 | $GREP -q "^[A-Za-z0-9]"
            if [ $? -eq 0 ]; then echo Success; else echo Failure; fi
        done
    done
fi

if [ "${TRANSFER}" == "YES" ]; then
	echo -e "\nVerify whether zone \"$zone\" on its master servers is able to be transferred..." 
	for itmaster in $(echo $DNS_PRIMARY_MASTER $DNS_PSEUDO_MASTERS); do
	    for remote in $(echo $masters); do
	        echo -e "  $itmaster tries transferring zone from $remote...\t\c"
    	    echo "dig @${remote} -t axfr $zone +tcp +short 2>/dev/null" \
		    	| ssh $itmaster bash 2>/dev/null | head -1 | $GREP -q "^[A-Za-z0-9]"
	        if [ $? -eq 0 ]; then echo Success; else echo Failure; fi
	    done
	done
fi
